<template>
    <div class="app-container">
        <div class="table-wrapper">
            <h4>水库大坝易损性管理</h4>
            <el-form class="form-inline" :inline="true" ref="queryRef" :rules="rules" label-position="right" :model="params"
                label-width="200px">
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="编号：" class="form-item" prop="cipvCode">
                            <el-input v-model="params.cipvCode" placeholder="" :disabled="true" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="类型：" class="form-item" prop="cipvType">
                            <el-select v-model="params.cipvType" placeholder="请选择" class="form-select" disabled clearable>
                                <el-option v-for="item in cipvTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="设防情况：" class="form-item" prop="fortification">
                            <el-select v-model="params.fortification" placeholder="请选择" class="form-select" disabled
                                clearable>
                                <el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="年代：" class="form-item" prop="years">
                            <el-select v-model="params.years" placeholder="请选择" class="form-select" clearable disabled>
                                <el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="维护人：" class="form-item" prop="userName">
                            <el-input v-model="params.userName" placeholder="" clearable disabled/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <el-form-item label="维护人所属单位：" class="form-item" prop="maintainerUnit">
                            <el-input v-model="params.maintainerUnit" placeholder="" clearable disabled/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="11">
                        <el-form-item label="维护时间:" class="form-item" prop="createTime">
                            <el-date-picker v-model="params.createTime" type="date" value-format="YYYY-MM-DD"
                                placeholder="选择日期" disabled>
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11"></el-col>
                </el-row>
            </el-form>
            <el-form :inline="true" ref="tableRef" :rules="rules" label-position="right" :model="tableFormData">
                <h4>地震易损性矩阵</h4>
                <el-table class="listTables" ref="multipleTableRef" border :data="tableFormData.tableData"
                    style="width: 100%" @selection-change="handleSelectionChange"
                    :cell-style="{ border: '1px solid #e5ebf7' }"
                    :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
                    <el-table-column prop="damage" label="破坏程度" align="right" width="150">
                        <el-table-column prop="intensity" label="烈度" width="150">
                        </el-table-column>
                    </el-table-column>
                    <el-table-column header-align="center" align="center" label="基本完好">
                        <template #default="scope">
                            <el-form-item :prop="`tableData.${scope.$index}.basicIntact`" :rules="rules.basicIntact">
                                <span v-if="!scope.row.isEdit">
                                    {{ scope.row.basicIntact }}
                                </span>
                                <el-input v-else v-model="scope.row.basicIntact" size="small" type="number"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column header-align="center" align="center" label="轻微破坏">
                        <template #default="scope">
                            <el-form-item :prop="`tableData.${scope.$index}.slightDamage`" :rules="rules.slightDamage">
                                <span v-if="!scope.row.isEdit">
                                    {{ scope.row.slightDamage }}
                                </span>
                                <el-input v-else v-model="scope.row.slightDamage" size="small" type="number"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column header-align="center" align="center" label="中等破坏">
                        <template #default="scope">
                            <el-form-item :prop="`tableData.${scope.$index}.moderateDamage`" :rules="rules.moderateDamage">
                                <span v-if="!scope.row.isEdit">
                                    {{ scope.row.moderateDamage }}
                                </span>
                                <el-input v-else v-model="scope.row.moderateDamage" size="small" type="number"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column header-align="center" align="center" label="严重破坏">
                        <template #default="scope">
                            <el-form-item :prop="`tableData.${scope.$index}.badlyDamaged`" :rules="rules.badlyDamaged">
                                <span v-if="!scope.row.isEdit">
                                    {{ scope.row.badlyDamaged }}
                                </span>
                                <el-input v-else v-model="scope.row.badlyDamaged" size="small" type="number"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column header-align="center" align="center" label="倒塌">
                        <template #default="scope">
                            <el-form-item :prop="`tableData.${scope.$index}.collapse`" :rules="rules.collapse">
                                <span v-if="!scope.row.isEdit">
                                    {{ scope.row.collapse }}
                                </span>
                                <el-input v-else v-model="scope.row.collapse" size="small" type="number"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right">
                        <template #default="scope">
                            <el-button type="text" size="small" @click="handleBrickModify(scope.$index, scope.row)">
                                {{ scope.row.isEdit ? '应用' : '修改' }}
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { reactive, toRefs } from "vue";
// 引入接口
import { getInfo } from '@/api/login';
import { queryDataByNumber, updateData } from "@/api/majorEnginVulnerAnalysis/majorEnginVulnerAnalysis.js";
// 状态管理模块
import useDictStore from '@/store/modules/dict';
// 获取pinia
const dictStore = useDictStore();

// 获取当前实例
const { proxy } = getCurrentInstance();

// 当前路由
const route = useRoute();

//最多保留N小数 ,N 在 options {decimals: N} 中定义
const positivedecimals = (rule, value, callback) => {
    value = String(value);
    if (
        value.indexOf(".") != -1 &&
        (value.split(".").length > rule.options.decimals ||
            value.split(".")[0] === "" ||
            value.split(".")[1] === "")
    ) {
        callback(new Error()); //防止输入多个小数点
    } else if (
        value.indexOf(".") != -1 &&
        value.split(".")[1].length > rule.options.decimals
    ) {
        callback(new Error()); //小数点后两位
    } else {
        callback();
    }
};

const data = reactive({
    // 表单参数
    params: {
        cipvCode: "",//编号
        cipvType: "",//类型
        years: "",//年代
        fortification: "", //设防情况
        createTime: "",//维护时间
        userName: "", //维护人
        maintainerUnit: "", //维护人所属单位
    },
    rules: {
        cipvCode: [
            { required: true, message: '', trigger: 'blur' },
        ],
        fortification: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        years: [
            { required: true, message: '请选择', trigger: 'change' }
        ],
        cipvType: [
            { required: true, message: '', trigger: 'blur' }
        ],
        basicIntact: [
            { required: true, message: "请输入正确数值，最多保留两位小数", trigger: "blur" },
            {
                message: "请输入正确数值，最多保留两位小数",
                validator: positivedecimals,
                options: { decimals: 2 },
                trigger: ["change", "blur"],
            },
        ],
        slightDamage: [
            { required: true, message: "请输入正确数值，最多保留两位小数", trigger: "blur" },
            {
                message: "请输入正确数值，最多保留两位小数",
                validator: positivedecimals,
                options: { decimals: 2 },
                trigger: ["change", "blur"],
            },
        ],
        moderateDamage: [
            { required: true, message: "请输入正确数值，最多保留两位小数", trigger: "blur" },
            {
                message: "请输入正确数值，最多保留两位小数",
                validator: positivedecimals,
                options: { decimals: 2 },
                trigger: ["change", "blur"],
            },
        ],
        badlyDamaged: [
            { required: true, message: "请输入正确数值，最多保留两位小数", trigger: "blur" },
            {
                message: "请输入正确数值，最多保留两位小数",
                validator: positivedecimals,
                options: { decimals: 2 },
                trigger: ["change", "blur"],
            },
        ],
        collapse: [
            { required: true, message: "请输入正确数值，最多保留两位小数", trigger: "blur" },
            {
                message: "请输入正确数值，最多保留两位小数",
                validator: positivedecimals,
                options: { decimals: 2 },
                trigger: ["change", "blur"],
            },
        ],
    },
    // 设防情况
    fortificationOptions: dictStore.fortificationOptions || [],
    // 年份
    yearsOptions: dictStore.yearsOptions1 || [],
    //候选值：重力坝、拱坝、支墩坝、预应力坝、其他
    cipvTypeOptions: [
        {
            value: '重力坝',
            label: '重力坝'
        }, {
            value: '拱坝',
            label: '拱坝'
        }, {
            value: '支墩坝',
            label: '支墩坝'
        }, {
            value: '预应力坝',
            label: '预应力坝'
        }, {
            value: '其他',
            label: '其他'
        }
    ],

    //表格
    tableFormData: {
        tableData: [],
    }
})
const {
    params,
    fortificationOptions,
    yearsOptions,
    cipvTypeOptions,
    tableFormData,
    rules
} = toRefs(data);

// 获取用户
function getUserInfo(userId) {
    getInfo(userId).then(response => {
        params.value.userName = response.user.userName
        params.value.maintainerUnit = response.user.orgName
        //params.value.createTime = parseTime(new Date())
    });
};

//表格
const multipleTableRef = ref();
const multipleSelection = ref()
// 表格复选事件
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

//修改 保存
const handleBrickModify = (index, row) => {
    if (row.isEdit) {
        let query = [
            {
                "cipvId": row.cipvId,
                "basicIntact": row.basicIntact, //基本完好
                "slightDamage": row.slightDamage, //轻微破坏
                "moderateDamage": row.moderateDamage, //中等破坏
                "badlyDamaged": row.badlyDamaged, //严重破坏
                "collapse": row.collapse, //倒塌
                "cipvType": params.value.cipvType, //类型
                "fortification": params.value.fortification, //设防情况
                "years": params.value.years, //年代
                "majorProjectCategory": params.value.majorProjectCategory //重大工程类别
            }
        ]
        updateData(query).then((res) => {
            if (res.code === 200) {
                proxy.$modal.msgSuccess('修改成功!');
                row.isEdit = false;
            } else {
                proxy.$modal.msgError('修改失败!');
            }
        }).catch(err => {
            console.log(err);
        });
    } else {
        row.isEdit = true;
    }
}

// 挂载
onMounted(() => {
    const paramsp = { number: route.query.cipvCode }
    queryDataByNumber(paramsp).then((res) => {
        const rows = res.data;
        if (res.code === 200 && rows) {
            //循环遍历之前加上非空判断
            if (rows.length > 0) {
                tableFormData.value.tableData = []
                rows.forEach((item) => {
                    item.isEdit = false;
                    tableFormData.value.tableData.push(item);
                });
                // 绑定表格第一行数据
                params.value = { ...rows[0] };
                // 根据创建人获取用户信息
                if (params.value.createUser) {
                    getUserInfo(params.value.createUser);
                }
            }
        }
    }).catch(err => {
        console.log(err);
    });
});
</script>

<style lang="scss" scoped>
.table-wrapper {
    position: relative;

    h4 {
        font-size: 16px;
        font-weight: bold;
        color: #107ce5;
        text-align: center;
    }
}

.form-inline {
    .el-form-item {
        margin-right: 0;
    }
}
</style>

<style>
.el-table.listTables thead.is-group th {
    background: none;
}

.el-table.listTables thead.is-group tr:first-of-type th:first-of-type {
    border-bottom: none;
}

.el-table.listTables thead.is-group tr:first-of-type th:first-of-type:before {
    content: '';
    position: absolute;
    width: 1px;
    height: 85px;
    /*这里需要自己调整，根据td的宽度和高度*/
    top: 0;
    left: 0;
    background-color: grey;
    opacity: 0.3;
    display: block;
    transform: rotate(302deg);
    /*这里需要自己调整，根据线的位置*/
    transform-origin: top;
}

.el-table.listTables thead.is-group tr:last-of-type th:first-of-type:before {
    content: '';
    position: absolute;
    width: 1px;
    height: 88px;
    /*这里需要自己调整，根据td的宽度和高度*/
    bottom: 0;
    right: 0;
    background-color: grey;
    opacity: 0.3;
    display: block;
    transform: rotate(302deg);
    /*这里需要自己调整，根据线的位置*/
    transform-origin: bottom;
    /* background:red; */
}
</style>
